<template>
  <div class="project-config">
    <div class="template-tree">
      <CustomTitle title="模块" style="margin-bottom: 10px" />
      <a-scrollbar style="height: calc(100vh - 200px); overflow: scroll">
        <Tree v-model:value="standardId" @change="changeTree" :treeData="templateTree" :field="treeFieldNames">
          <template #default="{ node }">
            {{ node?.standardName }}{{ node.isDefault ? "（默认）" : "" }}
            <a-switch
              v-if="!node.children?.length"
              v-model="node.standardState"
              @change="changeSwitch(node)"
              :checked-value="1"
              :unchecked-value="0"
            />
          </template>
        </Tree>
      </a-scrollbar>
    </div>
    <div class="template-detail">
      <div class="template-detail-title">
        <CustomTitle title="工艺详情" />
        <div v-if="editing">设为默认 <a-checkbox v-model="isDefault" @change="setDefault as any"></a-checkbox></div>
        <div v-else><a-button type="outline" @click="editing = true">编辑</a-button></div>
      </div>
      <a-divider margin="0"></a-divider>
      <div class="form app-container">
        <a-form :model="form" auto-label-width ref="formRef">
          <div class="form-item">
            <a-form-item
              label="工艺标准说明"
              field="standardDesc"
              :rules="[
                { required: true, message: '请输入工艺标准说明' },
                { maxLength: 500, message: '长度不能超过500个字符' }
              ]"
            >
              <a-textarea auto-size v-model="form.standardDesc" v-if="editing" show-word-limit :max-length="500"></a-textarea>
              <div class="disabled-areatext" v-else>{{ form.standardDesc }}</div>
            </a-form-item>
            <div v-if="editing" class="cite" @click="cite('standardDesc')">引用平台标准</div>
          </div>
          <div class="form-item" :rules="[{ maxLength: 80, message: '长度不能超过80个字符' }]">
            <a-form-item label="优劣势说明" field="shortcomingDesc">
              <a-textarea v-model="form.shortcomingDesc" v-if="editing" show-word-limit :max-length="80"></a-textarea>
              <div class="disabled-areatext" v-else>{{ form.shortcomingDesc }}</div>
            </a-form-item>
            <div v-if="editing" class="cite" @click="cite('shortcomingDesc')">引用平台标准</div>
          </div>
          <div class="form-item">
            <a-form-item label="工艺标准图">
              <div class="img-list" ref="parent">
                <div class="img-container" ref="imgContainer">
                  <div v-for="item in form.picUrls">
                    <img :src="item" alt="" />
                    <div class="del" v-if="editing" @click="delImg(item)"><icon-close /></div>
                  </div>
                  <a-upload
                    v-if="(form.picUrls?.length < 9 || !form.picUrls) && editing"
                    :custom-request="(customRequestImg as any)"
                    multiple
                    :show-file-list="false"
                    :accept="'image/jpeg' || 'image/png'"
                    :disabled="!editing"
                  >
                    <template #upload-button>
                      <div :class="{ 'upload-img': true, disabled: !editing }">
                        <icon-plus />
                        点击上传
                      </div>
                    </template>
                  </a-upload>
                </div>
              </div>
              <span class="tip">只能上传jpg/png，且不超过10M，最大支持上传9张</span>
            </a-form-item>
            <div v-if="editing" class="cite" @click="cite('picUrls')">引用平台标准</div>
          </div>
          <div class="form-item">
            <a-form-item label="工艺标准视频">
              <a-upload
                class="custom"
                style="flex: 1"
                :custom-request="(customRequestVideo as any)"
                multiple
                :show-file-list="false"
                :accept="'video/avi' || 'video/mov' || 'video/mp4' || 'video/wmv'"
                v-if="editing"
              >
                <template #upload-button>
                  <div :class="{ 'upload-video': true, disabled: !editing }"><icon-upload /> 点击上传</div>
                </template>
              </a-upload>
              <div class="carousel" v-if="form.videoUrls?.length">
                <div class="carousel-container" ref="videoContainer">
                  <div v-for="item in form.videoUrls">
                    <video :src="item" controls></video>
                    <div class="del" v-if="editing" @click="delVideo(item)"><icon-close /></div>
                  </div>
                </div>
              </div>
              <div class="tip">只能上传 avi/mov/mp4/wmv 文件格式，单个不超过200MB，最大支持6个</div>
            </a-form-item>
            <div v-if="editing" class="cite" @click="cite('videoUrls')">引用平台标准</div>
          </div>
        </a-form>
        <div class="btn" v-if="editing">
          <a-button type="primary" @click="save">保存</a-button>
          <a-button @click="editing = false">取消</a-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from "vue";
import { Message } from "@arco-design/web-vue";
import type { Detail, StandardData, StandardDataItem } from "@/apis/projectConfig/type";
import {
  standardTemplateTree,
  standardTemplateDetail,
  standardTemplateEdit,
  changeTreeSwitch,
  defaultDetail,
  getCiteData
} from "@/apis/projectConfig";
import Tree from "@/views/system/components/Tree.vue";
import useMultipartOssStore from "@/stores/modules/multipartOssStore";
import { useElementSize } from "@vueuse/core";

const imgContainer = ref(null);
const videoContainer = ref(null);
const parent = ref(null);

const { height, width } = useElementSize(imgContainer);
const { height: videoHeight, width: videoWidth } = useElementSize(videoContainer);
const { height: parentHeight, width: parentWidth } = useElementSize(parent);

const multipartOssStore = useMultipartOssStore();
const treeFieldNames = {
  key: "standardId",
  title: "standardName",
  children: "children"
};

const getTempId = (tree: any[], id: string) => {
  for (const node of tree) {
    if (node.standardId === id) {
      return node.templateId;
    }
    if (node.children && node.children.length > 0) {
      const templateId: string = getTempId(node.children, id);
      if (templateId) {
        // 如果在子节点中找到了匹配的名称，返回该名称
        return templateId;
      }
    }
  }
  // 如果没有找到，返回null
  return null;
};
const cite = async (key: "picUrls" | "videoUrls" | "shortcomingDesc" | "standardDesc") => {
  if (!editing.value) return;
  const { data }: { data: any } = await getCiteData(getTempId(templateTree.value, standardId.value));
  form.value[key] = ["picUrls", "videoUrls"].includes(key) ? data[key].split(",") : data[key];
};
const standardId = ref("");
const templateTree = ref<StandardData[]>([]);
const form = ref<Detail>({
  standardDesc: "",
  shortcomingDesc: "",
  picUrls: [],
  videoUrls: [],
  isDefault: 0
});
const formRef = ref(null);
const isDefault = ref(false);
const isImgMax = ref(false);
const isVideoMax = ref(false);
/**
 * 进入页面默认选择第一个分类下的第一个选项
 */
const getChild = (tree: { [name: string]: any }) => {
  const traverse = (tree: { [name: string]: any }) => {
    if (!(tree.children && tree.children.length)) {
      standardId.value = tree.standardId;
    } else {
      traverse(tree.children[0]);
    }
  };
  traverse(tree);
};
const getTemplateTree = async (isDetail = false) => {
  const { data } = await standardTemplateTree();
  templateTree.value = data || [];
  if (!standardId.value) getChild(data[0]);
  if (isDetail) getDetail();
};
const editing = ref(true);
const getDetail = async () => {
  const { data } = await standardTemplateDetail(standardId.value);
  const picUrls: string[] = data.picUrls ? data.picUrls.split(",") : [];
  const videoUrls: string[] = data.videoUrls ? data.videoUrls.split(",") : [];
  form.value = { ...data, picUrls, videoUrls };
  isDefault.value = data.isDefault == 1;
  editing.value = !data.standardDesc;
};
/**
 * 上传图片
 */
const customRequestImg = async (option: any) => {
  const { fileItem } = option;
  const { file, name } = fileItem;
  const isJPGorPNG = ["image/jpeg", "image/png"].includes(file.type);
  if (!isJPGorPNG) {
    Message.error("图片格式不正确");
    return;
  }
  const isSize = file.size / 1024 / 1024 < 10;
  if (!isSize) Message.error("文件不能超过10M！");
  multipartOssStore.submit(`crm/${name}`, file).then(async () => {
    await multipartOssStore.setACL(`crm/${name}`, "public-read");
    const fileUrl = await multipartOssStore.signatureUrl(`crm/${name}`);
    const url = fileUrl.split("?")[0];
    if (!form.value.picUrls) {
      form.value.picUrls = [url];
    } else {
      if (form.value.picUrls.length < 8) {
        form.value.picUrls.push(url);
      } else {
        if (!isImgMax.value) Message.error("最多上传8张图片");
        isImgMax.value = true;
      }
    }
  });
};

/**
 * 上传视频
 */
const customRequestVideo = async (option: any) => {
  const { fileItem } = option;
  const { file, name } = fileItem;
  const isJPGorPNG = ["video/avi", "video/mov", "video/mp4", "video/wmv"].includes(file.type);
  if (!isJPGorPNG) {
    Message.error("图片格式不正确");
    return;
  }
  const isSize = file.size / 1024 / 1024 < 200;
  if (!isSize) Message.error("文件不能超过200M！");
  multipartOssStore.submit(`crm/${name}`, file).then(async () => {
    await multipartOssStore.setACL(`crm/${name}`, "public-read");
    const fileUrl = await multipartOssStore.signatureUrl(`crm/${name}`);
    const url = fileUrl.split("?")[0];
    if (!form.value.videoUrls) {
      form.value.videoUrls = [url];
    } else {
      if (form.value.videoUrls.length < 6) {
        form.value.videoUrls.push(url);
      } else {
        if (!isVideoMax.value) Message.error("最多上传6个视频");
        isVideoMax.value = true;
      }
    }
  });
};
/**
 * 移除图片
 */
const delImg = (item: string) => {
  form.value.picUrls = form.value.picUrls.filter((i: string) => i !== item);
};
/**移除视频 */
const delVideo = (item: string) => {
  form.value.videoUrls = form.value.videoUrls.filter((i: string) => i !== item);
};
/**保存 */
const save = () => {
  (formRef as any).value.validate(async (error: any) => {
    if (error == undefined) {
      const isDefault = form.value.isDefault ? 1 : 0;
      const picUrls = form.value.picUrls.join(",");
      const videoUrls = form.value.videoUrls.join(",");
      await standardTemplateEdit({ ...form.value, isDefault, picUrls, videoUrls });
      getDetail();
      Message.success("保存成功");
      editing.value = false;
    }
  });
};
const changeTree = () => {
  getDetail();
};
const setDefault = async (value: boolean) => {
  await defaultDetail(standardId.value, value ? 1 : 0);
  getTemplateTree();
};
const changeSwitch = async (item: StandardDataItem) => {
  try {
    await changeTreeSwitch(item.standardId, item.standardState);
    getTemplateTree();
  } catch (error) {
    getTemplateTree();
  }
};
onMounted(() => {
  getTemplateTree(true);
});
</script>

<style scoped lang="scss">
.project-config {
  @include flex;
  height: calc(100%);
  box-sizing: border-box;

  .template-tree {
    @include flex;
    flex-direction: column;
    width: 250px;
    height: 100%;
    border-right: 1px solid #dcdfe6;

    .title {
      padding: 20px 20px 0 20px;
    }
  }

  .template-detail {
    flex: 1;
    overflow-y: auto;
    height: 100%;

    .template-detail-title {
      display: flex;
      justify-content: space-between;
      height: 62px;
      padding: 0 20px;

      div {
        height: 100%;
        display: flex;
        align-items: center;
      }

      ::v-deep(.arco-checkbox-icon) {
        border-radius: 50%;
      }
    }

    .form-item {
      position: relative;

      .cite {
        position: absolute;
        top: 30px;
        left: 12px;
        color: #007dff;
        text-decoration: underline;
        cursor: pointer;
      }

      .disabled-areatext {
        border: 1px solid #f2f3f5;
        padding: 6px 12px;
        min-height: 52px;
        border-radius: 4px;
        box-sizing: border-box;
      }
      ::v-deep(.arco-textarea) {
        background: #f2f3f5;
      }
      ::v-deep(.arco-textarea-textarea) {
        border: none;
      }
    }

    .btn {
      width: 100%;
      display: flex;
      gap: 20px;
      justify-content: center;
    }

    .custom {
      color: #007dff;
      height: 82px;
      background: #f2f3f5;
      box-sizing: border-box;
      width: 100%;
      line-height: 80px;
    }

    .del {
      position: absolute;
      right: -4px;
      top: -4px;
      width: 12px;
      height: 12px;
      border-radius: 50%;
      background: #f53f3f;
      display: flex;
      align-items: center;
      justify-content: center;

      .arco-icon {
        color: white;
        font-size: 10px;
      }
    }

    ::v-deep(.arco-form-item-content) {
      display: block;
    }

    ::v-deep(.arco-form-item-content-flex) {
      flex-wrap: wrap;
    }

    .img-list {
      position: relative;
      height: 90px;
      overflow: auto;
      padding-top: 10px;

      .img-container {
        position: absolute;
        display: flex;
        gap: 10px;

        > div {
          width: 80px;
          height: 80px;
          position: relative;

          img {
            width: 100%;
            height: 100%;
          }
        }

        .upload-img {
          width: 80px;
          height: 80px;
          background: #f2f3f5;
          border-radius: 4px;
          display: grid;
          grid-template-columns: 1fr;
          place-items: center;
          color: #86909c;
          font-size: 12px;

          ::v-deep(.arco-icon) {
            color: #86909c;
            font-size: 24px;
            font-weight: bold;
          }
        }
      }
    }

    .upload-video {
      padding-left: 10px;
    }

    .arco-scrollbar {
      margin-top: 10px;
    }

    .carousel {
      position: relative;
      height: 94px;
      overflow: auto;
      padding-top: 10px;

      .carousel-container {
        position: absolute;
        display: flex;
        gap: 10px;

        > div {
          min-width: 118px;
          height: 82px;
          background: #ffffff;
          border-radius: 4px;
          border: 1px dashed #dcdfe6;
          position: relative;

          video {
            width: 100%;
            height: 100%;
          }
        }
      }
    }

    .tip {
      color: #86909c;
      font-size: 12px;
      margin-top: 10px;
    }
  }
}

:deep(.arco-tree) {
  flex: 1;
  overflow-y: auto;
}
</style>
